/**
 * @author wy
 */

//global value
var new_ratio = -1;
var old_ratio = -1;
var glo_tab3_new_ratio = -1;
var glo_tab3_old_ratio = -1;
//info about all lr_plot
//set in comp_lr() used by change_lr()
var glo_lr_info = {
				//plot_div_id: [values_x, values_y, plot_div_id, stat_div_id, x_label, y_label, title, show_line]
			  };
var glo_stored_items =  [];
var glo_stored_volatile_items =  [];

function auto_save(){
	for(var i=0; i<glo_stored_volatile_items.length; ++i){
		window.localStorage.setItem(glo_stored_volatile_items[i].id, glo_stored_volatile_items[i].value);
	}
	
	for(var i=0; i<glo_stored_items.length; ++i){
		window.localStorage.setItem("para"+i, glo_stored_items[i].value);
	}
}

function clear_tab3(){
	var tab3_items = $("#tab3_exp_input_div textarea");
	for(var i=0; i<tab3_items.length; ++i){
		tab3_items[i].value = "";
		window.localStorage.setItem(tab3_items[i].id, "");
	}
	
//	window.location.reload();
}

function clear_tab1(){
	var tab1_items = $("#input_data_div textarea");
	for(var i=0; i<tab1_items.length; ++i){
		tab1_items[i].value = "";
		window.localStorage.setItem(tab1_items[i].id, "");
	}
	
	window.location.reload();
}

function trim(str) 
{
    return String(str).replace(/^\s+|\s+$/g, '').valueOf();
};

function show_exp_plot(){
	do_show_exp_plot("exp_plot_div", $("#show_err_bar_exp").attr("checked"));
}

function do_show_exp_plot(plot_div, show_err_bar, data_num){
	//aei ratios data
	input = document.getElementById("exp_data").value;
	if(!input){
		alert("Pls input AEI Ratios!")
		return
	}
	input = trim(input);
	data = input.split("\n");
	//error data
	err_data = $("#error_data").attr("value");
	var err_data_arr = new Array();
	if (!err_data) {
		for (var i = 0; i < data.length; ++i) {
			err_data_arr[i] = "0.000";
		}
	}
	else {
		err_data = trim(err_data)
		err_data_arr = err_data.split("\n");
	}
	if(err_data_arr.length != data.length){
		alert("Number of Error data and AEI Ratios Should be equal!")
		return
	}
	if(!data_num){
		data_num = err_data_arr.length;
	}
	$("#data_num_div").html(""+err_data_arr.length);
	$("#compare_num_sel").val(""+err_data_arr.length)
	$("#data_num_div").css("display", "block");
//	alert(input);
	var ticks = new Array();
	var plot_data = new Array();
	for(i=0; i<data.length && i<data_num; ++i)
	{
		ticks[i] = (i+1)+"";
		plot_data[i] = parseFloat(data[i]);
	}
//			alert(data)
//			alert(ticks);
	if(show_err_bar) {
		var ohlc_data = new Array();
		var flt_err;
		for (var i = 0; i < plot_data.length && i<data_num; ++i) {
			flt_err = parseFloat(err_data_arr[i]);
			//						high			low		   close
			ohlc_data[i] = [i + 1, plot_data[i] + flt_err, plot_data[i] - flt_err, 0];
			
		}
		plot_it_errbar([plot_data, ohlc_data], ticks, plot_div, ['<b class=\"legend_per\">Experiment data</b>', "<b class=\"legend_per\">Experimental error</b>"], 0, ["#4BB2C5"]);
	}
	else {
		plot_it([plot_data], ticks, plot_div, ['<b class=\"legend_per\">Experiment data</b>'], 0, ["#4BB2C5"]);
	}
}

function show_model_plot(aei_arr, plot_div , data_num){
	var ticks = new Array();
	var plot_data = new Array();
	for(i=0; i<aei_arr.length && i<data_num; ++i)
	{
		ticks[i] = (i+1)+"";
		plot_data[i] = aei_arr[i]
	}
	plot_it([aei_arr], ticks, plot_div, ['<b class=\"legend_per\">Model</b>'], ["#EAA228"]);
}

function plot_it_errbar(datas, ticks, plot_div_id, label_names, ofst, colors){
	if(!ofst){
		ofst = 0;
	}
	if(!colors){
		colors = new Array("#4BB2C5", "#EAA228", "orange");
	}
	$("#"+plot_div_id).html("");
	var plot_series = new Array();
	for(var i=0; i<datas.length-1; ++i){
		plot_series[i] = {renderer:$.jqplot.BarRenderer,
						  rendererOptions: {barWidth : 7},
						  label: label_names[i],
						  color:colors[i]};
	}
	plot_series[datas.length-1] = {
						            renderer:$.jqplot.OHLCRenderer,
					                rendererOptions: {errorBar:true,offset:ofst},
									label: label_names[datas.length-1],
									color: '#5C5C5C'};
    $.jqplot(plot_div_id, datas, {
        seriesDefaults:{
			shadow: false,
			useNegativeColors: false,
			fillToZero: true,
        },
        series:plot_series,
        legend: {
            show: true,
            placement: 'insideGrid',
			location: "nw",
        },
        axes: {
            xaxis: {
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: ticks,
				tickOptions: {
					fontSize: "15px",
				},
				label: 'Sample number',
				labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
				labelOptions:{
					fontFamily: 'Georgia, Serif',
					fontSize: "18px",
//					textColor: "#000",
				},
            },
            yaxis: {
                pad: 1.3,
                tickOptions: {
					formatString: '%.2f',
					fontSize: "15px",
				},
				label: 'Log2AEI ratio',
				labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
				labelOptions:{
					fontFamily: 'Georgia, Serif',
					fontSize: "18px",
//					textColor: "#000",
				},
            }
        },
		highlighter: {
		      show: true,
//		      showMarker:false,
		      tooltipAxes: 'xy',
    	}
    });
}

function plot_it(datas, ticks, plot_div_id, label_names, colors)
{
	$("#"+plot_div_id).html("");
	if(!colors){
		colors = new Array("#4BB2C5", "#EAA228", "orange");
	}
	var plot_label = new Array();
	for(var i=0; i<label_names.length; ++i){
		plot_label[i] = {label:label_names[i],color:colors[i]};
	}
    $.jqplot(plot_div_id, datas, {
        seriesDefaults:{
			shadow: false,
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {fillToZero: true,
 			         	  	  barWidth : 7,
//							  barPadding: 5,
//							  barWidth: 15,
//							  barMargin: 10
							  },
			useNegativeColors: false,
        },

        series:plot_label,
        legend: {
            show: true,
            placement: 'insideGrid',
			location: "nw",
        },
        axes: {
            xaxis: {
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: ticks,
				tickOptions: {
					fontSize: "15px",
				},
				label: 'Sample number',
				labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
				labelOptions:{
					fontFamily: 'Georgia, Serif',
					fontSize: "18px",
//					textColor: "#000",
				}
            },
            yaxis: {
                pad: 1.30,
                tickOptions: {
					formatString: '%.2f',
					fontSize: "15px",
				},
				label: 'Log2AEI ratio',
				labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
				labelOptions:{
					fontFamily: 'Georgia, Serif',
					fontSize: "18px",
//					textColor: "#000",
				}
            }
        },
		highlighter: {
		      show: true,
//		      showMarker:false,
		      tooltipAxes: 'xy',
    	}
    });
}

function check_plus_dabm(val, dabmObj)
{	
	dabmObj.is_plus_neg = 1;
	if(-1*val>dabmObj.dabm_pos_min){
		dabmObj.dabm_pos_min = -1*val;
	}	
}

function check_min_dabm(val, dabmObj)
{	
	dabmObj.is_min_neg = 1;
	if(val<dabmObj.dabm_neg_max){
		dabmObj.dabm_neg_max = val;
	}	
}

function func_est(data_arr, is_max)
{
	data_arr.sort();
	if(is_max)
		return data_arr[1];
	return data_arr[0];
}

function obj_to_string(obj){
	ret = ""
	for(var i in obj){
		ret += i+":";
		ret += obj[i]+";";
	}
	return ret
}

function get_options(){
	options = {"err_bar":true, "data_num":0, "exp_plot":true, "model_plot":true};
	//....
	options["err_bar"] = $("#comp_show_err_bar_cb").attr("checked");
	options["exp_plot"] = $("#comp_show_exp_cb").attr("checked");
	options["model_plot"] = $("#comp_show_model_cb").attr("checked");
	//model selection
	options["abcm_model"] = false;
	options["multi_model"] = false;
	options["addi_model"] = false;
	var checked_model_name = $("input:radio[@name='model_sel']:checked").val();
	options[checked_model_name] = true;
	
	options["data_num"] = parseInt($("#compare_num_sel").val());
	options["pta_model"] = $("#pta_model_cb").attr("checked");

//	alert(obj_to_string(options));
	return options;
}

function comp_lr_compare(){
	auto_save();
	para_keys = ["PA","PB","PC","PM","DDAM","DDBM","DDCM","DDAB","DDAC","DDBC","j","k","l","m"];
	inputs = $("#tab3_model_input_div .para_input");
	paras = {};
	k_idx = 0;
	for(var i=0; i<inputs.length; ++i,++k_idx){
		paras[para_keys[k_idx]] = inputs[i].value;
	}
	if(!paras["PA"] || paras["PA"]=="-" || paras["PB"]=="-" || paras["PB"]=="-"){
		alert("Please input all the parameters!");
		return;
	}
	var paras1 = new Array();
	var keys_2locus = new Array("j", "PA", "PB", "PM", "k", "DDAM", "DDBM", "DDAB");
	for (var i in keys_2locus) {
		paras1[i] = parseFloat(paras[keys_2locus[i]]);
	}
	$("#tab3_para_PC,#tab3_para_DDCM,#tab3_para_DDAC,#tab3_para_DDBC,#tab3_para_l").attr("value", "-");
	
	var ld_ret_obj = comp_3rd_order_ld(paras1);
	var paras = ld_ret_obj["paras"];
	var matr_base = ld_ret_obj["matr_base"];
	var dabm = ld_ret_obj["dabm"];
	var no_solution = ld_ret_obj["solution"];
	ld_ret_obj = null;
	
	show_matrix('tab3_matr_div', matr_base, [ "P(ABM)","P(AbM)","P(aBM)","P(abM)","P(ABm)","P(Abm)","P(aBm)","P(abm)"]);
	
	//show calculated
	$("#tab3_para_Pa").html(paras[2].toFixed(3));
	$("#tab3_para_Pb").html(paras[4].toFixed(3));
	$("#tab3_para_Pc").html("-");
	$("#tab3_para_Pm").html(paras[6].toFixed(3));
	$("#tab3_para_DAM").html(paras[9].toFixed(3));
	$("#tab3_para_DBM").html(paras[11].toFixed(3));
	$("#tab3_para_DCM").html("-");
	$("#tab3_para_DAB").html(paras[13].toFixed(3));
	$("#tab3_para_DAC").html("-");
	$("#tab3_para_DBC").html("-");
	if(no_solution){
		$("#tab3_para_DABM").html("<b style=\"color:red\">No Solution(0.000)</b>")
	}else{
		$("#tab3_para_DABM").html(dabm.toFixed(3));
	}
	$("#tab3_para_DACM").html("-");
	$("#tab3_para_DBCM").html("-");
	$("#tab3_para_DABC").html("-");
	$("#tab3_para_DABCM").html("-");
	
	//frequency array
	// -j 0 j
	var freq_arr = new Array();
	freq_arr[0] = matr_base[3]*matr_base[7] + matr_base[7]*matr_base[7] + matr_base[3]*matr_base[3] + matr_base[7]*matr_base[3];
	freq_arr[1] =   matr_base[1]*matr_base[6] + matr_base[2]*matr_base[5] + matr_base[5]*matr_base[2] + matr_base[6]*matr_base[1] 
				  + matr_base[5]*matr_base[6] + matr_base[6]*matr_base[5] + matr_base[1]*matr_base[2] + matr_base[2]*matr_base[1];
	freq_arr[2] =   matr_base[0]*matr_base[7] + matr_base[3]*matr_base[4] + matr_base[0]*matr_base[3] + matr_base[3]*matr_base[0] 
				  + matr_base[4]*matr_base[3] + matr_base[7]*matr_base[0] + matr_base[4]*matr_base[7] + matr_base[7]*matr_base[4];
	freq_arr[3] = matr_base[1]*matr_base[7] + matr_base[3]*matr_base[5]+ matr_base[5]*matr_base[7] + matr_base[7]*matr_base[5]
				  + matr_base[1]*matr_base[3]+ matr_base[3]*matr_base[1] + matr_base[5]*matr_base[3]+ matr_base[7]*matr_base[1];
	freq_arr[4] = matr_base[1]*matr_base[5] + matr_base[1]*matr_base[1] + matr_base[5]*matr_base[5] + matr_base[5]*matr_base[1];
	freq_arr[5] = matr_base[0]*matr_base[4] + matr_base[4]*matr_base[0] + matr_base[0]*matr_base[0] + matr_base[4]*matr_base[4];
	freq_arr[6] =  matr_base[0]*matr_base[5] + matr_base[1]*matr_base[4] + matr_base[4]*matr_base[1] + matr_base[5]*matr_base[0]
				 + matr_base[0]*matr_base[1] + matr_base[1]*matr_base[0] + matr_base[4]*matr_base[5] + matr_base[5]*matr_base[4];
	freq_arr[7] =  matr_base[0]*matr_base[6] + matr_base[2]*matr_base[4] + matr_base[4]*matr_base[2] + matr_base[6]*matr_base[0]
				 + matr_base[0]*matr_base[2] + matr_base[2]*matr_base[0] + matr_base[4]*matr_base[6] + matr_base[6]*matr_base[4];
	freq_arr[8] =  matr_base[2]*matr_base[6] + matr_base[6]*matr_base[2] + matr_base[2]*matr_base[2] + matr_base[6]*matr_base[6];
	freq_arr[9] =  matr_base[2]*matr_base[7] + matr_base[3]*matr_base[6] + matr_base[6]*matr_base[3] + matr_base[7]*matr_base[2]
				 + matr_base[2]*matr_base[3] + matr_base[3]*matr_base[2] + matr_base[6]*matr_base[7] + matr_base[7]*matr_base[6];

	var freq_arr_orig = new Array();
	for(var i in freq_arr){
		freq_arr_orig[i] = freq_arr[i];
	}
	
//	alert(freq_arr);
	var freq_sum = 0.0;
	for(var i in freq_arr){
		if(freq_arr[i] < 0.0001){
			freq_arr[i] = 0.0;
		}
		freq_sum += freq_arr[i];
	}

	//get delta data input
	var exp_delta_arr = trim($("#tab3_delta_ct_data").attr("value")).split("\n");
	var rVal_arr_exp_dict = {
		"A"	:	trim($("#tab3_A_data").attr("value")).split("\n"),
		"B"	:	trim($("#tab3_B_data").attr("value")).split("\n"),
		"C"	:	trim($("#tab3_C_data").attr("value")).split("\n"),
	}
	
	//check if the number of exp_delta_arr's and B_arr's data is equal
	var rVal = $("input[type=radio][name=exp_abc][checked=checked]").val()
	if(exp_delta_arr.length != rVal_arr_exp_dict[rVal].length){
		alert("the number of ΔCt and "+rVal+" should be the same!");
		return;
	}
	for(var i=0; i<exp_delta_arr.length; ++i){
		exp_delta_arr[i] = parseFloat(exp_delta_arr[i]);
		rVal_arr_exp_dict[rVal][i] = parseInt(rVal_arr_exp_dict[rVal][i]);
	}
	
	comp_lr(rVal_arr_exp_dict[rVal], exp_delta_arr, "tab3_lr_plot_exp", "tab3_lr_stat_exp", "0:aa    1:aA    2:AA", "ΔCt", "Experimental data", true);
		
	var scale_ratio = exp_delta_arr.length / freq_sum;
	glo_tab3_old_ratio = exp_delta_arr.length / freq_sum;
	if (glo_tab3_new_ratio > 0) {
		scale_ratio = glo_tab3_new_ratio;
	}
	//scale freq_arr
	var scaled_sum = scale_freq(scale_ratio, freq_arr, exp_delta_arr.length);
	
	//aei array
	var aei_arr = new Array();
	aei_arr[0] = 0.00;
	var temp = Math.pow(2, paras[0]) + Math.pow(2, paras[7]);
	aei_arr[1] = Math.log(temp)/Math.log(2) - 1;
	temp = Math.pow(2, (paras[0]+paras[7])) + 1;
	aei_arr[2] = Math.log(temp)/Math.log(2) - 1;
	temp = Math.pow(2, paras[0]) + 1;
	aei_arr[3] = Math.log(temp)/Math.log(2) - 1;
	aei_arr[4] = paras[0]
	aei_arr[5] = paras[0]+paras[7];
	temp = Math.pow(2, paras[7]) + 1;
	aei_arr[9] = Math.log(temp)/Math.log(2) - 1;
	aei_arr[6] = paras[0] + aei_arr[9];
	aei_arr[7] = paras[7] + aei_arr[3];
	aei_arr[8] = paras[7];
	
	key_arr = ["0", "(j+k)''", "(j+k)'", "j'", "j", "j+k", "j+k'", "j'+K", "k", "k'"];
	show_jkl_matr("tab3_jkl_matr_div", key_arr, freq_arr_orig, freq_arr, aei_arr, scale_ratio, exp_delta_arr.length, scaled_sum);
	
	var rVal_base_dict = {
		"A"	:	[0, 1, 1, 1, 2, 2, 2, 1, 0, 0],
		"B"	:	[0, 1, 1, 0, 0, 2, 1, 2, 2, 1],
	}
	
	var rVal_base = rVal_base_dict[$("#model_abc_sel_form").val()];
	var rVal_arr_model = new Array();
	var model_delta_arr = new Array();
	var plot_data = new Array();
	
	for(var i=0,k=0; i<freq_arr.length; ++i){
		for(var j=0; j<freq_arr[i]; ++j,++k){
			model_delta_arr[k] = aei_arr[i];
			rVal_arr_model[k] = rVal_base[i];
		}
	}
	
	
	comp_lr(rVal_arr_model, model_delta_arr, "tab3_lr_plot_model", "tab3_lr_stat_model", "0:aa    1:aA    2:AA", "ΔCt", "Model", true);
	
}

function comp_model()
{
	auto_save();
	//get options
	options = get_options();
	
	if(!options["model_plot"]){
		if (options["exp_plot"]) {
			do_show_exp_plot("comp_plot_div", options["err_bar"], options["data_num"]);
			return;
		}
		else {
			$("#comp_plot_div").html("");
			return
		}
	}
	
	para_keys = ["PA","PB","PC","PM","DDAM","DDBM","DDCM","DDAB","DDAC","DDBC","j","k","l","m"];
	inputs = $("#para_col_input .para_input");
	paras = {};
	k_idx = 0;
	for(var i=0; i<inputs.length; ++i,++k_idx){
		paras[para_keys[k_idx]] = inputs[i].value;
	}
	//additive model
	if(options["addi_model"]){
		if(!paras["PA"] || paras["PA"]=="-" || paras["PB"]=="-" || paras["PB"]=="-"){
			alert("Please input all the parameters!");
			return;
		}
		var paras_2locus = new Array();
		var keys_2locus = new Array("j", "PA", "PB", "PM", "k", "DDAM", "DDBM", "DDAB");
		for (var i in keys_2locus) {
			paras_2locus[i] = parseFloat(paras[keys_2locus[i]]);
		}
		$("#para_PC,#para_DDCM,#para_DDAC,#para_DDBC,#para_l").attr("value", "-");
		comp_model_addi(paras_2locus, options);
	}
	//pta model
	else if(options["pta_model"]){
		var paras_pta = {}
		var keys_pta = new Array("j", "PA", "PB", "PM", "m", "DDAM", "DDBM", "DDAB");
		for (var i in keys_pta) {
			paras_pta[keys_pta[i]] = parseFloat(paras[keys_pta[i]]);
			paras_pta[i] = parseFloat(paras[keys_pta[i]]);
		}
		$("#para_PC, #para_DDCM, #para_DDAC, #para_DDBC, #para_k, #para_l").attr("value", "-");
		comp_model_pta(paras_pta, options);
	}
	else if(!paras["PB"] || paras["PB"] == "-"){
		var paras_1locus = {}
		var keys_1locus = new Array("j", "PA", "PM", "DDAM");
		for (var i in keys_1locus) {
			paras_1locus[keys_1locus[i]] = parseFloat(paras[keys_1locus[i]]);
		}
		$("#para_PB, #para_PC,#para_DDBM,#para_DDCM,#para_DDAB,#para_DDAC,#para_DDBC,#para_k,#para_l").attr("value", "-");
		comp_model_1locus(paras_1locus, options);
	}else if (!paras["PC"] || paras["PC"] == "-") {
		var paras_2locus = new Array();
		var keys_2locus = new Array("j", "PA", "PB", "PM", "k", "DDAM", "DDBM", "DDAB");
		for (var i in keys_2locus) {
			paras_2locus[i] = parseFloat(paras[keys_2locus[i]]);
		}
		$("#para_PC,#para_DDCM,#para_DDAC,#para_DDBC,#para_l").attr("value", "-");
		comp_model_2locus(paras_2locus, options);
	}else{
		for(var key in paras){
			paras[key] = parseFloat(paras[key]);
		}
		comp_model_3locus(paras, options);
	}		
}

function constrain_2locus(paras){
	var comb = ["AM", "BM", "AB"];
	var lower1,lower2,upper1,upper2;
	for(var i in comb){
		upper1 = comb[i][0];
		upper2 = comb[i][1];
		lower1 = upper1.toLowerCase();
		lower2 = upper2.toUpperCase();
		up_bound = Math.max(paras["P"+upper1]*paras["P"+lower2], paras["P"+lower1]*paras["P"+upper2]);
		low_bound = Math.min(paras["P"+upper1]*paras["P"+upper2], paras["P"+lower1]*paras["P"+lower2]);
		if(paras["D"+comb[i]]<low_bound || paras["D"+comb[i]]>up_bound){
			alert("Constrain of D("+comb[i]+") not satisfied");
		}
	}
	if(paras["DAB"]+paras["DAM"]+paras["DBM"] < -paras["PA"]*paras["PB"]*paras["PM"]-paras["Pa"]*paras["Pb"]*paras["Pm"]){
		alert("Constrain of \"D(AB) + D(AM) + D(BM) ≥ -P(A)P(B)P(M) – P(a)P(b)P(m)\" not satisfied");
	}
	if(paras["DAB"]-paras["DAM"]-paras["DBM"] < -paras["PA"]*paras["PB"]*paras["Pm"]-paras["Pa"]*paras["Pb"]*paras["PM"]){
		alert("Constrain of \"D(AB) – D(AM) – D(BM) ≥ -P(A)P(B)P(m) – P(a)P(b)P(M)\" not satisfied");
	}
	if(paras["DAB"]-paras["DAM"]+paras["DBM"] < paras["PA"]*paras["Pb"]*paras["PM"]+paras["Pa"]*paras["PB"]*paras["Pm"]){
		alert("Constrain of \"D(AB) – D(AM) + D(BM) ≤  P(A)P(b)P(M) + P(a)P(B)P(m)\" not satisfied");
	}
	if(paras["DAB"]+paras["DAM"]-paras["DBM"] < paras["PA"]*paras["Pb"]*paras["Pm"]+paras["Pa"]*paras["PB"]*paras["PM"]){
		alert("Constrain of \"D(AB) + D(AM) – D(BM) ≤  P(A)P(b)P(m) + P(a)P(B)P(M)\" not satisfied");
	}
}

function constrain_3locus(paras){
	paras["P0ABM"] =  paras["PA"]*paras["PB"]*paras["PM"]  + paras["PA"]*paras["DBM"]  + paras["PB"]*paras["DAM"]  + paras["PM"]*paras["DAB"];
    paras["P0aBM"] =  paras["Pa"]*paras["PB"]*paras["PM"]  + paras["Pa"]*paras["DBM"]  - paras["PB"]*paras["DAM"]  - paras["PM"]*paras["DAB"];
    paras["P0AbM"] =  paras["PA"]*paras["Pb"]*paras["PM"]  - paras["PA"]*paras["DBM"]  + paras["Pb"]*paras["DAM"]  - paras["PM"]*paras["DAB"];
    paras["P0abM"] =  paras["Pa"]*paras["Pb"]*paras["PM"]  - paras["Pa"]*paras["DBM"]  - paras["Pb"]*paras["DAM"]  + paras["PM"]*paras["DAB"];
    paras["P0ABm"] =  paras["PA"]*paras["PB"]*paras["Pm"]  - paras["PA"]*paras["DBM"]  - paras["PB"]*paras["DAM"]  + paras["Pm"]*paras["DAB"];
    paras["P0aBm"] =  paras["Pa"]*paras["PB"]*paras["Pm"]  - paras["Pa"]*paras["DBM"]  + paras["PB"]*paras["DAM"]  - paras["Pm"]*paras["DAB"];
    paras["P0Abm"] =  paras["PA"]*paras["Pb"]*paras["Pm"]  + paras["PA"]*paras["DBM"]  - paras["Pb"]*paras["DAM"]  - paras["Pm"]*paras["DAB"];
    paras["P0abm"] =  paras["Pa"]*paras["Pb"]*paras["Pm"]  + paras["Pa"]*paras["DBM"]  + paras["Pb"]*paras["DAM"]  + paras["Pm"]*paras["DAB"];
	var up_bound,low_bound;
	up_bound = Math.min(paras["P0ABm"],paras["P0AbC"],paras["P0aBC"],paras["P0abc"])
	low_bound = Math.max(-paras["P0ABM"],-paras["P0Abc"],-paras["P0aBc"],-paras["P0abC"])
	if(paras["DABM"]>up_bound || paras["DABM"]<low_bound){
		alert("Constrain of D(ABM) not satisfied");
	}
}

function constrain_4locus(paras){
}

function comp_model_3locus(paras, options){
	var paras_3locus = new Array();
	var keys_3locus = [
						["j", "PA", "PB", "PM", "k", "DDAM", "DDBM", "DDAB"],
						["j", "PA", "PC", "PM", "k", "DDAM", "DDCM", "DDAC"],
						["j", "PB", "PC", "PM", "k", "DDBM", "DDCM", "DDBC"],
						["j", "PA", "PB", "PC", "k", "DDAC", "DDBC", "DDAB"]
					  ];
	var keys_need = ["DABM","DACM","DBCM","DABC"];
	var ld_ret_obj;
	var paras_2locus;
	var keys_2locus;
	var no_solution = {};
	for(var i=0; i<keys_3locus.length; ++i){
		keys_2locus = keys_3locus[i];
		paras_2locus = new Array();
		for(var j=0; j<keys_2locus.length; ++j){
			paras_2locus[j] = paras[keys_2locus[j]];
		}
		ld_ret_obj = comp_3rd_order_ld(paras_2locus);
		//[D(ABM), D(ACM), D(BCM), D(ABC)]
		paras[keys_need[i]] = ld_ret_obj["dabm"];
		no_solution[keys_need[i]] = ld_ret_obj["solution"];
		ld_ret_obj = null;
		//is this sequence right?
		//alert(ld_ret_obj["dabm"]);
	}
	//other paras
	paras["Pa"] = 1 - paras["PA"];
	paras["Pb"] = 1 - paras["PB"];
	paras["Pc"] = 1 - paras["PC"];
	paras["Pm"] = 1 - paras["PM"];
	paras["DAM"] = paras["DDAM"]*(func_est([paras["PA"], paras["PM"]])-paras["PA"]*paras["PM"]);
	paras["DBM"] = paras["DDBM"]*(func_est([paras["PB"], paras["PM"]])-paras["PB"]*paras["PM"]);
	paras["DCM"] = paras["DDCM"]*(func_est([paras["PC"], paras["PM"]])-paras["PC"]*paras["PM"]);
	paras["DAB"] = paras["DDAB"]*(func_est([paras["PA"], paras["PB"]])-paras["PA"]*paras["PB"]);
	paras["DAC"] = paras["DDAC"]*(func_est([paras["PA"], paras["PC"]])-paras["PA"]*paras["PC"]);
	paras["DBC"] = paras["DDBC"]*(func_est([paras["PB"], paras["PC"]])-paras["PB"]*paras["PC"]);
	paras["DABCM"] = 0;
	
	var matr_base = new Array();
	//PABCM
	matr_base[0] = paras["PA"]*paras["PB"]*paras["PC"]*paras["PM"] +
                paras["PA"]*paras["PB"]*paras["DCM"] + paras["PA"]*paras["PC"]*paras["DBM"] + paras["PA"]*paras["PM"]*paras["DBC"] + paras["PB"]*paras["PC"]*paras["DAM"] +
                paras["PB"]*paras["PM"]*paras["DAC"] + paras["PC"]*paras["PM"]*paras["DAB"]+
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] +
                paras["PA"]*paras["DBCM"] + paras["PB"]*paras["DACM"] + paras["PC"]*paras["DABM"] + paras["PM"]*paras["DABC"] +
                paras["DABCM"];

	//PAbCM
	matr_base[1] = paras["PA"]*paras["Pb"]*paras["PC"]*paras["PM"] +
                paras["PA"]*paras["Pb"]*paras["DCM"] - paras["PA"]*paras["PC"]*paras["DBM"] - paras["PA"]*paras["PM"]*paras["DBC"] + paras["Pb"]*paras["PC"]*paras["DAM"] + 
                paras["Pb"]*paras["PM"]*paras["DAC"] - paras["PC"]*paras["PM"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] -
                paras["PA"]*paras["DBCM"] + paras["Pb"]*paras["DACM"] - paras["PC"]*paras["DABM"] - paras["PM"]*paras["DABC"] -
                paras["DABCM"];

	
	//PaBCM
	matr_base[2] = paras["Pa"]*paras["PB"]*paras["PC"]*paras["PM"] +
                paras["Pa"]*paras["PB"]*paras["DCM"] + paras["Pa"]*paras["PC"]*paras["DBM"] + paras["Pa"]*paras["PM"]*paras["DBC"] - paras["PB"]*paras["PC"]*paras["DAM"] -
                paras["PB"]*paras["PM"]*paras["DAC"] - paras["PC"]*paras["PM"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] +
                paras["Pa"]*paras["DBCM"] - paras["PB"]*paras["DACM"] - paras["PC"]*paras["DABM"] - paras["PM"]*paras["DABC"] -
                paras["DABCM"];

	//PabCM
	matr_base[3] = paras["Pa"]*paras["Pb"]*paras["PC"]*paras["PM"] +
                paras["Pa"]*paras["Pb"]*paras["DCM"] - paras["Pa"]*paras["PC"]*paras["DBM"] - paras["Pa"]*paras["PM"]*paras["DBC"] - paras["Pb"]*paras["PC"]*paras["DAM"] -
                paras["Pb"]*paras["PM"]*paras["DAC"] + paras["PC"]*paras["PM"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] -
                paras["Pa"]*paras["DBCM"] - paras["Pb"]*paras["DACM"] + paras["PC"]*paras["DABM"] + paras["PM"]*paras["DABC"] +
                paras["DABCM"];

	//PABcM
	matr_base[4] = paras["PA"]*paras["PB"]*paras["Pc"]*paras["PM"] -
                paras["PA"]*paras["PB"]*paras["DCM"] + paras["PA"]*paras["Pc"]*paras["DBM"] - paras["PA"]*paras["PM"]*paras["DBC"] + paras["PB"]*paras["Pc"]*paras["DAM"] -
                paras["PB"]*paras["PM"]*paras["DAC"] + paras["Pc"]*paras["PM"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] -
                paras["PA"]*paras["DBCM"] - paras["PB"]*paras["DACM"] + paras["Pc"]*paras["DABM"] - paras["PM"]*paras["DABC"] -
                paras["DABCM"];


	//PAbcM
	matr_base[5] = paras["PA"]*paras["Pb"]*paras["Pc"]*paras["PM"] -
                paras["PA"]*paras["Pb"]*paras["DCM"] - paras["PA"]*paras["Pc"]*paras["DBM"] + paras["PA"]*paras["PM"]*paras["DBC"] + paras["Pb"]*paras["Pc"]*paras["DAM"] -
                paras["Pb"]*paras["PM"]*paras["DAC"] - paras["Pc"]*paras["PM"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] +
                paras["PA"]*paras["DBCM"] - paras["Pb"]*paras["DACM"] - paras["Pc"]*paras["DABM"] + paras["PM"]*paras["DABC"] +
                paras["DABCM"];

	//PaBcM
	matr_base[6] = paras["Pa"]*paras["PB"]*paras["Pc"]*paras["PM"] -
                paras["Pa"]*paras["PB"]*paras["DCM"] + paras["Pa"]*paras["Pc"]*paras["DBM"] - paras["Pc"]*paras["PM"]*paras["DBC"] - paras["PB"]*paras["Pc"]*paras["DAM"] + 
                paras["PB"]*paras["PM"]*paras["DAC"] - paras["Pc"]*paras["PM"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] -
                paras["Pa"]*paras["DBCM"] + paras["PB"]*paras["DACM"] - paras["Pc"]*paras["DABM"] + paras["PM"]*paras["DABC"] +
                paras["DABCM"];

	//PabcM
	matr_base[7] = paras["Pa"]*paras["Pb"]*paras["Pc"]*paras["PM"] -
                paras["Pa"]*paras["Pb"]*paras["DCM"] - paras["Pa"]*paras["Pc"]*paras["DBM"] + paras["Pa"]*paras["PM"]*paras["DBC"] - paras["Pb"]*paras["Pc"]*paras["DAM"] + 
                paras["Pb"]*paras["PM"]*paras["DAC"] + paras["Pc"]*paras["PM"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] +
                paras["Pa"]*paras["DBCM"] + paras["Pb"]*paras["DACM"] + paras["Pc"]*paras["DABM"] - paras["PM"]*paras["DABC"] -
                paras["DABCM"];

	//PABCm
	matr_base[8] = paras["PA"]*paras["PB"]*paras["PC"]*paras["Pm"] -
                paras["PA"]*paras["PB"]*paras["DCM"] - paras["PA"]*paras["PC"]*paras["DBM"] + paras["PA"]*paras["Pm"]*paras["DBC"] - paras["PB"]*paras["PC"]*paras["DAM"] + 
                paras["PB"]*paras["Pm"]*paras["DAC"] + paras["PC"]*paras["Pm"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] -
                paras["PA"]*paras["DBCM"] - paras["PB"]*paras["DACM"] - paras["PC"]*paras["DABM"] + paras["Pm"]*paras["DABC"] -
                paras["DABCM"];


	//PAbCm
	matr_base[9] = paras["PA"]*paras["Pb"]*paras["PC"]*paras["Pm"] -
                paras["PA"]*paras["Pb"]*paras["DCM"] + paras["PA"]*paras["PC"]*paras["DBM"] - paras["PA"]*paras["Pm"]*paras["DBC"] - paras["Pb"]*paras["PC"]*paras["DAM"] + 
                paras["Pb"]*paras["Pm"]*paras["DAC"] - paras["PC"]*paras["Pm"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] +
                paras["PA"]*paras["DBCM"] - paras["Pb"]*paras["DACM"] + paras["PC"]*paras["DABM"] - paras["Pm"]*paras["DABC"] +
                paras["DABCM"];
	
	//PaBCm
	matr_base[10] = paras["Pa"]*paras["PB"]*paras["PC"]*paras["Pm"] -
                paras["Pa"]*paras["PB"]*paras["DCM"] - paras["Pa"]*paras["PC"]*paras["DBM"] + paras["Pa"]*paras["Pm"]*paras["DBC"] + paras["PB"]*paras["PC"]*paras["DAM"] -
                paras["PB"]*paras["Pm"]*paras["DAC"] - paras["PC"]*paras["Pm"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] -
                paras["Pa"]*paras["DBCM"] + paras["PB"]*paras["DACM"] + paras["PC"]*paras["DABM"] - paras["Pm"]*paras["DABC"] +
                paras["DABCM"];

	//PabCm
	matr_base[11] = paras["Pa"]*paras["Pb"]*paras["PC"]*paras["Pm"] -
                paras["Pa"]*paras["Pb"]*paras["DCM"] + paras["Pa"]*paras["PC"]*paras["DBM"] - paras["Pa"]*paras["Pm"]*paras["DBC"] + paras["Pb"]*paras["PC"]*paras["DAM"] -
                paras["Pb"]*paras["Pm"]*paras["DAC"] + paras["PC"]*paras["Pm"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] +
                paras["Pa"]*paras["DBCM"] + paras["Pb"]*paras["DACM"] - paras["PC"]*paras["DABM"] + paras["Pm"]*paras["DABC"] -
                paras["DABCM"];

	//PABcm
	matr_base[12] = paras["PA"]*paras["PB"]*paras["Pc"]*paras["Pm"] +
                paras["PA"]*paras["PB"]*paras["DCM"] - paras["PA"]*paras["Pc"]*paras["DBM"] - paras["PA"]*paras["Pm"]*paras["DBC"] - paras["PB"]*paras["Pc"]*paras["DAM"] - 
                paras["PB"]*paras["Pm"]*paras["DAC"] + paras["Pc"]*paras["Pm"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] +
                paras["PA"]*paras["DBCM"] + paras["PB"]*paras["DACM"] - paras["Pc"]*paras["DABM"] - paras["Pm"]*paras["DABC"] +
                paras["DABCM"];

	//PAbcm
	matr_base[13] = paras["PA"]*paras["Pb"]*paras["Pc"]*paras["Pm"] +
                paras["PA"]*paras["Pb"]*paras["DCM"] + paras["PA"]*paras["Pc"]*paras["DBM"] + paras["PA"]*paras["Pm"]*paras["DBC"] - paras["Pb"]*paras["Pc"]*paras["DAM"] -
                paras["Pb"]*paras["Pm"]*paras["DAC"] - paras["Pc"]*paras["Pm"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] -
                paras["PA"]*paras["DBCM"] + paras["Pb"]*paras["DACM"] + paras["Pc"]*paras["DABM"] + paras["Pm"]*paras["DABC"] -
                paras["DABCM"];
				
	//PaBcm
	matr_base[14] = paras["Pa"]*paras["PB"]*paras["Pc"]*paras["Pm"] +
                paras["Pa"]*paras["PB"]*paras["DCM"] - paras["Pa"]*paras["Pc"]*paras["DBM"] - paras["Pa"]*paras["Pm"]*paras["DBC"] + paras["PB"]*paras["Pc"]*paras["DAM"] + 
                paras["PB"]*paras["Pm"]*paras["DAC"] - paras["Pc"]*paras["Pm"]*paras["DAB"] -
                paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"] +
                paras["Pa"]*paras["DBCM"] - paras["PB"]*paras["DACM"] + paras["Pc"]*paras["DABM"] + paras["Pm"]*paras["DABC"] -
                paras["DABCM"];

	//Pabcm
	matr_base[15] = paras["Pa"]*paras["Pb"]*paras["Pc"]*paras["Pm"] +
                paras["Pa"]*paras["Pb"]*paras["DCM"] + paras["Pa"]*paras["Pc"]*paras["DBM"] + paras["Pa"]*paras["Pm"]*paras["DBC"] + paras["Pb"]*paras["Pc"]*paras["DAM"] + 
                paras["Pb"]*paras["Pm"]*paras["DAC"] + paras["Pc"]*paras["Pm"]*paras["DAB"] +
                paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"] -
                paras["Pa"]*paras["DBCM"] - paras["Pb"]*paras["DACM"] - paras["Pc"]*paras["DABM"] - paras["Pm"]*paras["DABC"] +
                paras["DABCM"];
	
	if(options["abcm_model"]){
		matr_base[15] -= paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"];
		matr_base[14] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"]);
		matr_base[13] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"]);
		matr_base[12] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
		matr_base[11] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"])
		matr_base[10] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
		matr_base[9] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
		matr_base[8] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"])
		matr_base[7] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"])
		matr_base[6] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
		matr_base[5] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
		matr_base[4] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"])
		matr_base[3] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
		matr_base[2] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"])
		matr_base[1] -= (-paras["DAB"]*paras["DCM"] - paras["DAC"]*paras["DBM"] - paras["DAM"]*paras["DBC"])
		matr_base[0] -= (paras["DAB"]*paras["DCM"] + paras["DAC"]*paras["DBM"] + paras["DAM"]*paras["DBC"])
	}
	
	//DABCM
	var dabmObj = new Object();
	dabmObj.is_plus_neg = 0;
	dabmObj.is_min_neg = 0;
	dabmObj.dabm_pos_min = -1;
	dabmObj.dabm_neg_max = 1;
	plus_idx = [0,3,5,6,9,10,12,15];
	min_idx = [1,2,4,7,8,11,13,14];
	for(var i=0; i<plus_idx.length; ++i){
		if(matr_base[plus_idx[i]]<0){
			check_plus_dabm(matr_base[plus_idx[i]], dabmObj);
		}
	}
	for(var i=0; i<min_idx.length; ++i){
		if(matr_base[min_idx[i]]<0){
			check_min_dabm(matr_base[min_idx[i]], dabmObj);
		}
	}
	if(dabmObj.is_min_neg){
		if(dabmObj.is_plus_neg){
//				alert("No Solution!");
				no_solution["DABCM"] = true;
		}else{
//			alert(dabmObj.dabm_neg_max);
			paras["DABCM"] = dabmObj.dabm_neg_max;
		}
	}else if(dabmObj.is_plus_neg){
//			alert(dabmObj.dabm_pos_min);
			paras["DABCM"] = dabmObj.dabm_pos_min;
	}
	if(paras["DABCM"] != 0){
		for(var i=0; i<plus_idx.length; ++i){
			matr_base[plus_idx[i]] += paras["DABCM"];
		}
		for(var i=0; i<min_idx.length; ++i){
			matr_base[min_idx[i]] -= paras["DABCM"];
		}
	}
	
	show_matrix_3locus(matr_base);
	
	//show calculated
	$("#para_Pa").html(paras["Pa"].toFixed(3));
	$("#para_Pb").html(paras["Pb"].toFixed(3));
	$("#para_Pc").html(paras["Pc"].toFixed(3));
	$("#para_Pm").html(paras["Pm"].toFixed(3));
	$("#para_DAM").html(paras["DAM"].toFixed(3));
	$("#para_DBM").html(paras["DBM"].toFixed(3));
	$("#para_DCM").html(paras["DCM"].toFixed(3));
	$("#para_DAB").html(paras["DAB"].toFixed(3));
	$("#para_DAC").html(paras["DAC"].toFixed(3));
	$("#para_DBC").html(paras["DBC"].toFixed(3));
	if(no_solution["DABM"]){
		$("#para_DABM").html("<b style=\"color:red\">No Solution(0.000)</b>");
	}else{
		$("#para_DABM").html(paras["DABM"].toFixed(6));
	}
	if(no_solution["DACM"]){
		$("#para_DACM").html("<b style=\"color:red\">No Solution(0.000)</b>");
	}else{
		$("#para_DACM").html(paras["DACM"].toFixed(6));
	}
	if(no_solution["DBCM"]){
		$("#para_DBCM").html("<b style=\"color:red\">No Solution(0.000)</b>");
	}else{
		$("#para_DBCM").html(paras["DBCM"].toFixed(6));
	}
	if(no_solution["DABC"]){
		$("#para_DABC").html("<b style=\"color:red\">No Solution(0.000)</b>");
	}else{
		$("#para_DABC").html(paras["DABC"].toFixed(6));
	}
	if(no_solution["DABCM"]){
		$("#para_DABCM").html("<b style=\"color:red\">No Solution(0.000)</b>");
	}else{
		$("#para_DABCM").html(paras["DABCM"].toFixed(6));
	}
//	alert(matr_base);
//	alert(paras["DABCM"].toFixed(10));
	
	//compute frequency
	var freq_arr = new Array();
	//j+k+l
	freq_arr[0] = matr_base[0]*matr_base[15];
	//j+k-l
	freq_arr[1] = matr_base[4]*matr_base[11];
	//j-k+l
	freq_arr[2] = matr_base[1]*matr_base[14];
	//j-k-l
	freq_arr[3] = matr_base[5]*matr_base[10];
	//j+k
	freq_arr[4] = matr_base[4]*matr_base[15]+matr_base[0]*matr_base[11];
	//j+l
	freq_arr[5] = matr_base[0]*matr_base[14]+matr_base[1]*matr_base[15];
	//j-k
	freq_arr[6] = matr_base[1]*matr_base[10] + matr_base[5]*matr_base[14];
	//j-l
	freq_arr[7] = matr_base[5]*matr_base[11] + matr_base[4]*matr_base[10];
	//k+l
	freq_arr[8] = matr_base[2]*matr_base[15] + matr_base[0]*matr_base[13];
	//k-l
	freq_arr[9] = matr_base[4]*matr_base[9] + matr_base[6]*matr_base[11];
	//j
	freq_arr[10] = matr_base[5]*matr_base[15] + matr_base[4]*matr_base[14] + matr_base[0]*matr_base[10] + matr_base[1]*matr_base[11];
	//k
	freq_arr[11] = matr_base[6]*matr_base[15] + matr_base[0]*matr_base[9] + matr_base[2]*matr_base[11] + matr_base[4]*matr_base[13];
	//l
	freq_arr[12] = matr_base[3]*matr_base[15] + matr_base[2]*matr_base[14] + matr_base[1]*matr_base[13] + matr_base[0]*matr_base[12];
	//0
	freq_arr[13] = matr_base[7]*matr_base[15] + matr_base[6]*matr_base[14] + matr_base[5]*matr_base[13] + matr_base[4]*matr_base[12] +
				   matr_base[3]*matr_base[11] + matr_base[2]*matr_base[10] + matr_base[1]*matr_base[9] + matr_base[0]*matr_base[8];
	//-l
	freq_arr[14] = matr_base[7]*matr_base[11] + matr_base[6]*matr_base[10] + matr_base[5]*matr_base[9] + matr_base[4]*matr_base[8];
	//-k
	freq_arr[15] = matr_base[7]*matr_base[14] + matr_base[5]*matr_base[12] + matr_base[3]*matr_base[10] + matr_base[1]*matr_base[8];
	//-j
	freq_arr[16] = matr_base[2]*matr_base[8] + matr_base[3]*matr_base[9] + matr_base[6]*matr_base[12] + matr_base[7]*matr_base[13];
	//-k-l
	freq_arr[17] = matr_base[5]*matr_base[8] + matr_base[7]*matr_base[10];
	//-k+l
	freq_arr[18] = matr_base[3]*matr_base[14] + matr_base[1]*matr_base[12];
	//-j-l
	freq_arr[19] = matr_base[6]*matr_base[8] + matr_base[7]*matr_base[9];
	//-j-k
	freq_arr[20] = matr_base[3]*matr_base[8] + matr_base[7]*matr_base[12];
	//-j+l
	freq_arr[21] = matr_base[3]*matr_base[13] + matr_base[2]*matr_base[12];
	//-j+k
	freq_arr[22] = matr_base[6]*matr_base[13] + matr_base[2]*matr_base[9];
	//-j-k+l
	freq_arr[23] = matr_base[3]*matr_base[12];
	//-j+k-l
	freq_arr[24] = matr_base[6]*matr_base[9];
	//-j+k+l
	freq_arr[25] = matr_base[2]*matr_base[13];
	//-j-k-l
	freq_arr[26] = matr_base[7]*matr_base[8];
	
	var freq_arr_orig = new Array();
	for(var i in freq_arr){
		freq_arr_orig[i] = freq_arr[i];
	}
	
//	alert(freq_arr);
	var freq_sum = 0.0;
	for(var i in freq_arr){
		if(freq_arr[i] < 0.0001){
			freq_arr[i] = 0.0;
		}
		freq_sum += freq_arr[i];
	}
	
	var scale_ratio = options["data_num"] / freq_sum;
	old_ratio = options["data_num"] / freq_sum;
	if (new_ratio > 0) {
		scale_ratio = new_ratio;
	}
	//scale freq_arr
	var scaled_sum = scale_freq(scale_ratio, freq_arr, options["data_num"]);
	
	//compute aei array
	var aei_arr = new Array();
	aei_arr[0] = paras["j"] + paras["k"] + paras["l"];
	aei_arr[1] = paras["j"] + paras["k"] - paras["l"];
	aei_arr[2] = paras["j"] - paras["k"] + paras["l"];
	aei_arr[3] = paras["j"] - paras["k"] - paras["l"];
	aei_arr[4] = paras["j"] + paras["k"];
	aei_arr[5] = paras["j"] + paras["l"];
	aei_arr[6] = paras["j"] - paras["k"];
	aei_arr[7] = paras["j"] - paras["l"];
	aei_arr[8] = paras["k"] + paras["l"];
	aei_arr[9] = paras["k"] - paras["l"];
	aei_arr[10] = paras["j"];
	aei_arr[11] = paras["k"];
	aei_arr[12] = paras["l"];
	aei_arr[13] = 0.010001;
	aei_arr[14] = -paras["l"];
	aei_arr[15] = -paras["k"];
	aei_arr[16] = -paras["j"];
	aei_arr[17] = -aei_arr[8];
	aei_arr[18] = -aei_arr[9];
	aei_arr[19] = -aei_arr[5];
	aei_arr[20] = -aei_arr[4];
	aei_arr[21] = -aei_arr[7];
	aei_arr[22] = -aei_arr[6];
	aei_arr[23] = -aei_arr[1];
	aei_arr[24] = -aei_arr[2];
	aei_arr[25] = -aei_arr[3];
	aei_arr[26] = -aei_arr[0];
	
	key_arr = ["j+k+l", "j+k-l", "j-k+l", "j-k-l", "j+k", "j+l", "j-k", "j-l", "k+l", "k-l", "j", "k", "l", "0", 
				"-l", "-k", "-j", "-k-l", "-k+l", "-j-l", "-j-k", "-j+l", "-j+k", "-j-k+l", "-j+k-l", "-j+k+l", "-j-k-l"]
	show_jkl_matr("jkl_matr_div", key_arr, freq_arr_orig, freq_arr, aei_arr, scale_ratio, options["data_num"], scaled_sum);
	
	var plot_data = new Array();
	for(var i=0,k=0; i<freq_arr.length; ++i){
		for(var j=0; j<freq_arr[i]; ++j,++k){
			plot_data[k] = aei_arr[i];
		}
	}
	plot_data.sort(function(a,b){return a-b;});
//	alert(plot_data);
	
	if(!options["exp_plot"]){
		show_model_plot(plot_data, "comp_plot_div", options["data_num"]);
		return
	}
	
	input = document.getElementById("exp_data").value;
	input = trim(input);
	var input_data = input.split("\n");
	var ticks = new Array();
	var exp_data = new Array();
	for(i=0; i<input_data.length && i<options["data_num"]; ++i)
	{
		ticks[i] = (i+1);
		exp_data[i] = parseFloat(input_data[i]);
	}
	
	//comp_lr
	comp_lr(plot_data, exp_data, "lr_plot", "lr_stat", "Experimental", "Model", "", true);
	
	if(!options["err_bar"]){
		plot_it([exp_data, plot_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>"], ["#4BB2C5", "#EAA228"]);
		return;
	}
	
	//plot errbar	
	var err_data_input = $("#error_data").val();
	var err_data = new Array();
	
	var err_data_arr = new Array();
	if (!err_data_input) {
		for (var i = 0; i < options["data_num"]; ++i) {
			err_data[i] = "0.000";
		}
	}
	else {
		err_data = trim(err_data_input).split("\n");
	}
	
	var ohlc_data = new Array();
	var flt_err;
	for(var i=0;i<err_data.length && i<options["data_num"]; ++i){
		flt_err = parseFloat(err_data[i]);
		//						high					low			   close
		ohlc_data[i] = [i+1, exp_data[i]+flt_err, exp_data[i]-flt_err, 0];
		
	}
	
	plot_it_errbar([exp_data, plot_data, ohlc_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>", "<b class=\"legend_per\">Experimental error</b>"], -7, ["#4BB2C5", "#EAA228"]);
}


function show_matrix_3locus(matr_base){
	var matr_div = $('#matr_div').html('').css({'font-size':'90%'});
	var matr_tab = $('<table>').attr('border', '1').css({"margin-right":"auto","margin-left":"auto"});
	
	//first row
	var tab_row = $('<tr>').append(
								$('<td>').html("&nbsp;").css('width', '15px')
						  ).append(
						  		$('<td>').html("&nbsp;")
						  );
	for(var i=0; i<matr_base.length; ++i){
		if (matr_base[i] + 0.0001 < 0) {
			tab_row.append($('<td>').html("<b style=\"color:red;\">" + matr_base[i].toFixed(3) + "</b>"))
		}
		else {
			if (matr_base[i] - 0.0001 < 0){
				tab_row.append($('<td>').html("0.000"))
			}else
				tab_row.append($('<td>').html(matr_base[i].toFixed(3)))
		}
	}
	matr_tab.append(tab_row);
	
	//second row
	tab_row = $('<tr>').append(
					  		$('<th>').html('<b style="color:white;">$$$$$</b>')
					  ).append(
					  		$('<th>').html("SNP3")
					  );
	var matr_heads = [ "P(ABCM)","P(AbCM)","P(aBCM)","P(abCM)","P(ABcM)","P(AbcM)","P(aBcM)","P(abcM)",
					   "P(ABCm)","P(AbCm)","P(aBCm)","P(abCm)","P(ABcm)","P(Abcm)","P(aBcm)","P(abcm)" ]
	for(var i=0; i<matr_heads.length; ++i){
		tab_row.append( $('<th>').html(matr_heads[i]) );
	}
	matr_tab.append(tab_row);
	
	//the rest rows
	matr_len = matr_base.length;
	for(var i=0; i<matr_len; ++i){
		tab_row = $("<tr>");
		if (matr_base[matr_len - i - 1] + 0.0001 < 0) {
			tab_row.append($('<td>').html("<b style=\"color:red;\">" + matr_base[matr_len - i - 1].toFixed(3) + "</b>"))
		}
		else {
			if (matr_base[i] - 0.0001 < 0){
				tab_row.append($('<td>').html("0.000"))
			}else
				tab_row.append($('<td>').html(matr_base[matr_len - i - 1].toFixed(3)))
		}
		tab_row.append( $('<th>').html(matr_heads[matr_len-i-1]) );
		for(var j=0; j<matr_len; ++j){
			var cell_val = matr_base[j]*matr_base[matr_len-i-1];
			if(cell_val+0.0001<0){
				tab_row.append( $('<td>').html('<b style="color:red;">'+cell_val.toFixed(3)+'</b>') );
			}else{
				if (cell_val - 0.0001 < 0){
					tab_row.append($('<td>').html("0.000"))
				}else
					tab_row.append( $('<td>').html(cell_val.toFixed(3)) );
			}
		}
		matr_tab.append(tab_row);
	}

	matr_div.append(matr_tab);
							
}

function comp_3rd_order_ld(paras1){
	var matr_base = new Array();
	var dabmObj = new Object();
	dabmObj.is_plus_neg = 0;
	dabmObj.is_min_neg = 0;
	dabmObj.dabm_pos_min = -1;
	dabmObj.dabm_neg_max = 1;
	var dabm = 0;
	var paras = new Array();
	paras[0] = paras1[0];
	paras[1] = paras1[1];
	paras[2] = 1-paras1[1];
	paras[3] = paras1[2];
	paras[4] = 1-paras1[2];
	paras[5] = paras1[3];
	paras[6] = 1-paras1[3];
	paras[7] = paras1[4];
	paras[8] = paras1[5];
	paras[9] = paras1[5]*(func_est([paras1[1], paras1[3]])-paras1[1]*paras1[3]);
	paras[10] = paras1[6];
	paras[11] = paras1[6]*(func_est([paras1[2], paras1[3]])-paras1[2]*paras1[3]);
	paras[12] = paras1[7];
	paras[13] = paras1[7]*(func_est([paras1[1], paras1[2]])-paras1[1]*paras1[2]);
	matr_base[0] = (paras[1]*paras[3]*paras[5])+(paras[1]*paras[11])+(paras[3]*paras[9])+(paras[5]*paras[13])
	matr_base[1] = (paras[1]*paras[4]*paras[5])-(paras[1]*paras[11])+(paras[4]*paras[9])-(paras[5]*paras[13])
	matr_base[2] = (paras[2]*paras[3]*paras[5])+(paras[2]*paras[11])-(paras[3]*paras[9])-(paras[5]*paras[13])
	matr_base[3] = (paras[2]*paras[4]*paras[5])-(paras[2]*paras[11])-(paras[4]*paras[9])+(paras[5]*paras[13])
	matr_base[4] = (paras[1]*paras[3]*paras[6])-(paras[1]*paras[11])-(paras[3]*paras[9])+(paras[6]*paras[13])
	matr_base[5] = (paras[1]*paras[4]*paras[6])+(paras[1]*paras[11])-(paras[4]*paras[9])-(paras[6]*paras[13])
	matr_base[6] = (paras[2]*paras[3]*paras[6])-(paras[2]*paras[11])+(paras[3]*paras[9])-(paras[6]*paras[13])
	matr_base[7] = (paras[2]*paras[4]*paras[6])+(paras[2]*paras[11])+(paras[4]*paras[9])+(paras[6]*paras[13])
	
//	alert(paras);
//	alert(matr_base);
//  for test
//	matr_base = [-0.2,0.2,0.1,-0.1,0.1,-0.3,-0.1,-0.1]
	plus_idx = [0,3,5,6]
	min_idx = [1,2,4,7]
	for(var i=0; i<plus_idx.length; ++i){
		if(matr_base[plus_idx[i]]<0){
			check_plus_dabm(matr_base[plus_idx[i]], dabmObj);
		}
	}
	for(var i=0; i<min_idx.length; ++i){
		if(matr_base[min_idx[i]]<0){
			check_min_dabm(matr_base[min_idx[i]], dabmObj);
		}
	}
	var no_solu_flag = false;
	if(dabmObj.is_min_neg){
		if(dabmObj.is_plus_neg){
//			alert("No Solution!");
			no_solu_flag = true;
		}else{
//			alert(dabmObj.dabm_neg_max);
			dabm = dabmObj.dabm_neg_max;
		}
	}else if(dabmObj.is_plus_neg){
//			alert(dabmObj.dabm_pos_min);
			dabm = dabmObj.dabm_pos_min;
	}
	if(dabm != 0){
		for(var i=0; i<plus_idx.length; ++i){
			matr_base[plus_idx[i]] += dabm;
		}
		for(var i=0; i<min_idx.length; ++i){
			matr_base[min_idx[i]] -= dabm;
		}
	}
	var ret_obj = {};
	ret_obj["paras"] = paras;
	ret_obj["matr_base"] = matr_base;
	ret_obj["dabm"] = dabm;
	ret_obj["solution"] = no_solu_flag;
	return ret_obj;
}

function scale_freq(scale_ratio, freq_arr, data_num){
	//scale frequency to options["data_num"]
	var freq_sum_scaled = 0;
	for(var i=0; i<freq_arr.length; ++i){
		freq_arr[i] *= scale_ratio;
		freq_arr[i] = Math.round(freq_arr[i]);
		freq_sum_scaled += freq_arr[i]
	}
//	alert(freq_arr);
//	alert(freq_sum_scaled);	
	//"round" freq
/*
	var delta_collect = 0;
	var rounded_freq;
	var delta_sum = options["data_num"];
	for(var i=0; i<freq_arr.length; ++i){
		rounded_freq = Math.round(freq_arr[i]);
		if(delta_collect+rounded_freq-freq_arr[i]<-1){
			rounded_freq += 1;
		}else if(delta_collect+rounded_freq-freq_arr[i]>1){
			rounded_freq -= 1;
		}
		delta_collect += rounded_freq-freq_arr[i];
		freq_arr[i] = rounded_freq;
		delta_sum -= rounded_freq;
	}
	if(freq_sum_scaled!=0){
		freq_arr[freq_arr.length-1] += delta_sum;
	}
*/	

//	alert(freq_arr);
	return freq_sum_scaled;
}

function comp_model_addi(paras1, options)
{
	
	var ld_ret_obj = comp_3rd_order_ld(paras1);
	var paras = ld_ret_obj["paras"];
	var matr_base = ld_ret_obj["matr_base"];
	var dabm = ld_ret_obj["dabm"];
	var no_solution = ld_ret_obj["solution"];
	ld_ret_obj = null;
	
	show_matrix('matr_div', matr_base, [ "P(ABM)","P(AbM)","P(aBM)","P(abM)","P(ABm)","P(Abm)","P(aBm)","P(abm)"]);
	
	//show calculated
	$("#para_Pa").html(paras[2].toFixed(3));
	$("#para_Pb").html(paras[4].toFixed(3));
	$("#para_Pc").html("-");
	$("#para_Pm").html(paras[6].toFixed(3));
	$("#para_DAM").html(paras[9].toFixed(3));
	$("#para_DBM").html(paras[11].toFixed(3));
	$("#para_DCM").html("-");
	$("#para_DAB").html(paras[13].toFixed(3));
	$("#para_DAC").html("-");
	$("#para_DBC").html("-");
	if(no_solution){
		$("#para_DABM").html("<b style=\"color:red\">No Solution(0.000)</b>")
	}else{
		$("#para_DABM").html(dabm.toFixed(3));
	}
	$("#para_DACM").html("-");
	$("#para_DBCM").html("-");
	$("#para_DABC").html("-");
	$("#para_DABCM").html("-");
	
	//frequency array
	// -j 0 j
	var freq_arr = new Array();
	freq_arr[0] = matr_base[3]*matr_base[4]*2;
	freq_arr[1] = matr_base[3]*matr_base[5]*2;
	freq_arr[2] = matr_base[3]*matr_base[6]*2;
	freq_arr[3] = matr_base[2]*matr_base[5]*2;
	freq_arr[4] = matr_base[2]*matr_base[4]*2;
	freq_arr[5] = matr_base[1]*matr_base[4]*2;
	freq_arr[6] = (matr_base[3]*matr_base[7] + matr_base[2]*matr_base[6] + matr_base[1]*matr_base[5] + matr_base[0]*matr_base[4])*2;
	freq_arr[7] = matr_base[2]*matr_base[7]*2;
	freq_arr[8] = matr_base[1]*matr_base[7]*2;
	freq_arr[9] = matr_base[1]*matr_base[6]*2;
	freq_arr[10] = matr_base[0]*matr_base[5]*2;
	freq_arr[11] = matr_base[0]*matr_base[6]*2;
	freq_arr[12] = matr_base[0]*matr_base[7]*2;

	var freq_arr_orig = new Array();
	for(var i in freq_arr){
		freq_arr_orig[i] = freq_arr[i];
	}
	
//	alert(freq_arr);
	var freq_sum = 0.0;
	for(var i in freq_arr){
		if(freq_arr[i] < 0.0001){
			freq_arr[i] = 0.0;
		}
		freq_sum += freq_arr[i];
	}

	var scale_ratio = options["data_num"] / freq_sum;
	old_ratio = options["data_num"] / freq_sum;
	if (new_ratio > 0) {
		scale_ratio = new_ratio;
	}
	//scale freq_arr
	var scaled_sum = scale_freq(scale_ratio, freq_arr, options["data_num"]);
	
	//aei array
	var aei_arr = new Array();
	var temp = Math.pow(2, paras[0]) + Math.pow(2, paras[7]);
	aei_arr[0] = -1*Math.log(temp)/Math.log(2);
	aei_arr[1] = -1*paras[0];
	aei_arr[2] = -1*paras[7];
	aei_arr[3] = -1*paras[0]+paras[7];
	aei_arr[4] = paras[7]-Math.log(temp)/Math.log(2);
	aei_arr[5] = paras[0]-Math.log(temp)/Math.log(2);
	aei_arr[6] = 0;
	aei_arr[7] = paras[7];
	aei_arr[8] = paras[0];
	aei_arr[9] = paras[0] - paras[7];
	aei_arr[10] = Math.log(temp)/Math.log(2)-paras[0];
	aei_arr[11] = Math.log(temp)/Math.log(2)-paras[7];
	aei_arr[12] = Math.log(temp)/Math.log(2);
	
	key_arr = ["-(j+k)*", "-j", "-k", "-j+k", "k-(j+k)*", "j-(j+k)*", "0", "k", "j", "j-k", "(j+k)*-j", "(j+k)*-k", "(j+k)*"];
	show_jkl_matr("jkl_matr_div", key_arr, freq_arr_orig, freq_arr, aei_arr, scale_ratio, options["data_num"], scaled_sum);
	
	var plot_data = new Array();
	for(var i=0,k=0; i<freq_arr.length; ++i){
		for(var j=0; j<freq_arr[i]; ++j,++k){
			plot_data[k] = aei_arr[i];
		}
	}
	plot_data.sort(function(a,b){return a-b;});
//	alert(plot_data);
	
	if(!options["exp_plot"]){
		show_model_plot(plot_data, "comp_plot_div", options["data_num"]);
		return
	}
	
	input = document.getElementById("exp_data").value;
	input = trim(input);
	var input_data = input.split("\n");
	var ticks = new Array();
	var exp_data = new Array();
	for(i=0; i<input_data.length && i<options["data_num"]; ++i)
	{
		ticks[i] = (i+1);
		exp_data[i] = parseFloat(input_data[i]);
	}
	
	//comp_lr
	comp_lr(plot_data, exp_data, "lr_plot", "lr_stat", "Experiment", "Model", "", true);
	
	if(!options["err_bar"]){
		plot_it([exp_data, plot_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>"], ["#4BB2C5", "#EAA228"]);
		return;
	}
	
	//plot errbar	
	var err_data_input = $("#error_data").val();
	var err_data = new Array();
	
	var err_data_arr = new Array();
	if (!err_data_input) {
		for (var i = 0; i < options["data_num"]; ++i) {
			err_data[i] = "0.000";
		}
	}
	else {
		err_data = trim(err_data_input).split("\n");
	}
	
	var ohlc_data = new Array();
	var flt_err;
	for(var i=0;i<err_data.length && i<options["data_num"]; ++i){
		flt_err = parseFloat(err_data[i]);
		//						high					low			   close
		ohlc_data[i] = [i+1, exp_data[i]+flt_err, exp_data[i]-flt_err, 0];
		
	}
	
	plot_it_errbar([exp_data, plot_data, ohlc_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>", "<b class=\"legend_per\">Experimental error</b>"], -7, ["#4BB2C5", "#EAA228"]);	
}

function comp_model_2locus(paras1, options)
{
	
	var ld_ret_obj = comp_3rd_order_ld(paras1);
	var paras = ld_ret_obj["paras"];
	var matr_base = ld_ret_obj["matr_base"];
	var dabm = ld_ret_obj["dabm"];
	var no_solution = ld_ret_obj["solution"];
	ld_ret_obj = null;
	
	//show calculated
	$("#para_Pa").html(paras[2].toFixed(3));
	$("#para_Pb").html(paras[4].toFixed(3));
	$("#para_Pc").html("-");
	$("#para_Pm").html(paras[6].toFixed(3));
	$("#para_DAM").html(paras[9].toFixed(3));
	$("#para_DBM").html(paras[11].toFixed(3));
	$("#para_DCM").html("-");
	$("#para_DAB").html(paras[13].toFixed(3));
	$("#para_DAC").html("-");
	$("#para_DBC").html("-");
	if(no_solution){
		$("#para_DABM").html("<b style=\"color:red\">No Solution(0.000)</b>")
	}else{
		$("#para_DABM").html(dabm.toFixed(3));
	}
	$("#para_DACM").html("-");
	$("#para_DBCM").html("-");
	$("#para_DABC").html("-");
	$("#para_DABCM").html("-");
	
	
//	alert(matr_base);
	//show matrix
	var matr_div = document.getElementById("matr_div");
	matr_div.innerHTML = "";
	var matr_tab = document.createElement("table");
	matr_tab.border = "1";
	matr_tab.style.marginLeft = "auto";
	matr_tab.style.marginRight = "auto";
	
	//first row
	var tab_row = document.createElement("tr")
	var row_cell = document.createElement("td");
	row_cell.innerHTML = "&nbsp;";
	tab_row.appendChild(row_cell);
	var row_cell = document.createElement("td");
	row_cell.innerHTML = "&nbsp;";
	tab_row.appendChild(row_cell);
	for (var i = 0; i < matr_base.length; ++i) {
		var row_cell = document.createElement("td");
		if (matr_base[i] + 0.00001 < 0) {
			row_cell.innerHTML = "<b style=\"color:red;\">" + matr_base[i].toFixed(3) + "</b>";
		}
		else {
			row_cell.innerHTML = matr_base[i].toFixed(3);
		}
		tab_row.appendChild(row_cell);		
	}
	matr_tab.appendChild(tab_row);
	
	//second row
	var tab_row = document.createElement("tr")
	var row_cell = document.createElement("td");
	row_cell.innerHTML = "&nbsp;";
	tab_row.appendChild(row_cell);
	var head_row_data = ["SNP2", "P(ABM)", "P(AbM)", "P(aBM)", "P(abM)", "P(ABm)", "P(Abm)", "P(aBm)", "P(abm)"]
	for(var i=0; i<head_row_data.length; ++i){
		var row_cell = document.createElement("th");
		row_cell.innerHTML = head_row_data[i];
		tab_row.appendChild(row_cell);
	}
	matr_tab.appendChild(tab_row);
	
	//remaining rows
	var cell_data = new Array();
	for(var i=0; i<matr_base.length; ++i){
		//first tow cells
		var tab_row = document.createElement("tr");
		var row_cell = document.createElement("td");
		if (matr_base[matr_base.length-i-1] + 0.00001 < 0) {
			row_cell.innerHTML = "<b style=\"color:red;\">" + matr_base[matr_base.length-i-1].toFixed(3) + "</b>";
		}
		else {
			row_cell.innerHTML = matr_base[matr_base.length-i-1].toFixed(3);
		}
		tab_row.appendChild(row_cell);
		var row_cell = document.createElement("th");
		row_cell.innerHTML = head_row_data[head_row_data.length-i-1];
		tab_row.appendChild(row_cell);
		//the rest cells
		for(var j=0; j<matr_base.length; ++j){
			var cell_val = matr_base[matr_base.length-i-1]*matr_base[j];
			var key = head_row_data[head_row_data.length-i-1]+head_row_data[j+1];
			cell_data[key] = cell_val;
			var row_cell = document.createElement("td");
			if (cell_val + 0.00001 < 0) {
				row_cell.innerHTML = "<b style=\"color:red;\">" + cell_val.toFixed(3) + "</b>";
			}
			else {
				row_cell.innerHTML = cell_val.toFixed(3);
			}			
			tab_row.appendChild(row_cell);			
		}
		matr_tab.appendChild(tab_row);
	}
//	alert(cell_data["P(ABM)P(ABM)"]);
	
	matr_div.appendChild(matr_tab);
	
	//compute frequency
	//				-(j+k)						-j									-k						-(j-k)									0										j-k						k									j						j+k
	var keys_need = [["P(ABm)P(abM)"], ["P(ABm)P(aBM)","P(Abm)P(abM)"], ["P(ABm)P(AbM)", "P(aBm)P(abM)"], ["P(Abm)P(aBM)"], ["P(ABm)P(ABM)","P(Abm)P(AbM)","P(aBm)P(aBM)","P(abm)P(abM)"], ["P(aBm)P(AbM)"],["P(Abm)P(ABM)","P(abm)P(aBM)"],["P(aBm)P(ABM)","P(abm)P(AbM)"],["P(abm)P(ABM)"]];
	var freq_arr = new Array();
	var aei_arr = new Array();
	var freq_sum = 0;
	for(var i=0; i<keys_need.length; ++i){
		key_group = keys_need[i];
		freq_arr[i] = 0;
		for(var j=0; j<key_group.length; ++j){
			freq_arr[i] += cell_data[key_group[j]]*2;
		}
		freq_sum += freq_arr[i];
	}
	
	var freq_arr_orig = new Array();
	for(var i in freq_arr){
		freq_arr_orig[i] = freq_arr[i];
	}

	var scale_ratio = options["data_num"] / freq_sum;
	old_ratio = options["data_num"] / freq_sum;
	if (new_ratio > 0) {
		scale_ratio = new_ratio;
	}
	//scale freq_arr
	var scaled_sum = scale_freq(scale_ratio, freq_arr, options["data_num"]);

	aei_arr[0] = -(paras[0]+paras[7]);
	aei_arr[1] = -(paras[0]);
	aei_arr[2] = -(paras[7]);
	aei_arr[3] = -(paras[0]-paras[7]);
	aei_arr[4] = 0.010001;
	aei_arr[5] = (paras[0]-paras[7]);
	aei_arr[6] = paras[7];
	aei_arr[7] = paras[0];
	aei_arr[8] = (paras[0]+paras[7]);
//	alert(aei_arr);

	//show jkl matrix
	show_jkl_matr("jkl_matr_div", ["-(j+k)", "-j", "-k", "-(j-k)", "0", "(j-k)", "k", "j", "(j+k)"], freq_arr_orig, freq_arr, aei_arr, scale_ratio, options["data_num"], scaled_sum);
	
	var plot_data = new Array();
	for(var i=0,k=0; i<freq_arr.length; ++i){
		for(var j=0; j<freq_arr[i]; ++j,++k){
			plot_data[k] = aei_arr[i];
		}
	}
	plot_data.sort(function(a,b){return a-b;});
//	alert(plot_data);
//	alert(plot_data.length);


	if(!options["exp_plot"]){
		show_model_plot(plot_data, "comp_plot_div", options["data_num"]);
		return
	}
	
	//show comparison graph
	var show_later_div = $(".show_later");
	for(var i=0; i<show_later_div.length; ++i){
		show_later_div[i].style.display = "block";
	}
	input = document.getElementById("exp_data").value;
	input = trim(input);
	var input_data = input.split("\n");
	var ticks = new Array();
	var exp_data = new Array();
	for(i=0; i<input_data.length && i<options["data_num"]; ++i)
	{
		ticks[i] = (i+1);
		exp_data[i] = parseFloat(input_data[i]);
	}
	
	//comp_lr
	comp_lr(plot_data, exp_data, "lr_plot", "lr_stat", "Experimental", "Model", "", true);
	
	if(!options["err_bar"]){
		plot_it([exp_data, plot_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>"], ["#4BB2C5", "#EAA228"]);
		return;
	}
	
	//plot errbar
	var err_data_input = $("#error_data").val();
	var err_data = new Array();
	
	var err_data_arr = new Array();
	if (!err_data_input) {
		for (var i = 0; i < options["data_num"]; ++i) {
			err_data[i] = "0.000";
		}
	}
	else {
		err_data = trim(err_data_input).split("\n");
	}
	
	var ohlc_data = new Array();
	var flt_err;
	for(var i=0;i<err_data.length && i<options["data_num"]; ++i){
		flt_err = parseFloat(err_data[i]);
		//						high					low			   close
		ohlc_data[i] = [i+1, exp_data[i]+flt_err, exp_data[i]-flt_err, 0];
		
	}
	
//	plot_it_errbar([exp_data, plot_data], ticks, "compare_err_plot", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>"]);
	test_data = [[[1, 136.01, 139.5, 134.53, 139.48],
  				 [2, 143.82, 144.56, 136.04, 136.97],
				 [3, 136.47, 146.4, 136, 144.67],
				 [4, 124.76, 135.9, 124.55, 135.81],
				 [5, 123.73, 129.31, 121.57, 122.5],
				 [6, 127.37, 130.96, 119.38, 122.42],
				 ],
				 [136, 140, 141, 130, 125, 125],
				 [133, 139, 139, 127, 128, 127]
				];
	test_ticks = [1,2,3,4,5,6];
//	alert(exp_data);
//	alert(plot_data);
//	alert(ohlc_data);
	plot_it_errbar([exp_data, plot_data, ohlc_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>", "<b class=\"legend_per\">Experimental error</b>"], -7, ["#4BB2C5", "#EAA228"]);
//	plot_it([[136, 140, 141, 130, 125, 125]], [1,2,3,4,5,6], "compare_err_plot", ["<b class=\"legend_per\">Experiment data</b>"]);
	
}

function comp_model_1locus(paras, options){
//	alert(paras);
	paras["Pa"] = 1 - paras["PA"];
	paras["Pm"] = 1- paras["PM"];
	paras["DAM"] = paras["DDAM"]*(func_est([paras["PA"], paras["PM"]])-paras["PA"]*paras["PM"]);
	var matr_base = new Array();
	matr_base[0] = paras["PA"]*paras["PM"] + paras["DAM"];
	matr_base[1] = paras["Pa"]*paras["PM"] - paras["DAM"];
	matr_base[2] = paras["PA"]*paras["Pm"] - paras["DAM"];
	matr_base[3] = paras["Pa"]*paras["Pm"] + paras["DAM"];
	
	show_matrix('matr_div', matr_base, [ "P(AM)","P(aM)","P(Am)","P(am)"]);
	
	//show calculated
	$("#para_Pa").html(paras["Pa"].toFixed(3));
	$("#para_Pm").html(paras["Pm"].toFixed(3));
	$("#para_DAM").html(paras["DAM"].toFixed(3));
	
	//frequency array
	// -j 0 j
	var freq_arr = new Array();
	freq_arr[0] = matr_base[1]*matr_base[2]*2;
	freq_arr[1] = (matr_base[0]*matr_base[2] + matr_base[1]*matr_base[3])*2
	freq_arr[2] = matr_base[0]*matr_base[3]*2
	
	var freq_arr_orig = new Array();
	for(var i in freq_arr){
		freq_arr_orig[i] = freq_arr[i];
	}
	
//	alert(freq_arr);
	var freq_sum = 0.0;
	for(var i in freq_arr){
		if(freq_arr[i] < 0.0001){
			freq_arr[i] = 0.0;
		}
		freq_sum += freq_arr[i];
	}
	
	var scale_ratio = options["data_num"] / freq_sum;
	old_ratio = options["data_num"] / freq_sum;
	if (new_ratio > 0) {
		scale_ratio = new_ratio;
	}
	//scale freq_arr
	var scaled_sum = scale_freq(scale_ratio, freq_arr, options["data_num"]);
	
	//aei array
	var aei_arr = new Array();
	aei_arr[0] = -1*paras["j"];
	aei_arr[1] =0.010001;
	aei_arr[2] = paras["j"]
	
	key_arr = ["-j", "0", "j"]
	show_jkl_matr("jkl_matr_div", key_arr, freq_arr_orig, freq_arr, aei_arr, scale_ratio, options["data_num"], scaled_sum);
	
	var plot_data = new Array();
	for(var i=0,k=0; i<freq_arr.length; ++i){
		for(var j=0; j<freq_arr[i]; ++j,++k){
			plot_data[k] = aei_arr[i];
		}
	}
	plot_data.sort(function(a,b){return a-b;});
//	alert(plot_data);
	
	if(!options["exp_plot"]){
		show_model_plot(plot_data, "comp_plot_div", options["data_num"]);
		return
	}
	
	input = document.getElementById("exp_data").value;
	input = trim(input);
	var input_data = input.split("\n");
	var ticks = new Array();
	var exp_data = new Array();
	for(i=0; i<input_data.length && i<options["data_num"]; ++i)
	{
		ticks[i] = (i+1);
		exp_data[i] = parseFloat(input_data[i]);
	}
	
	//comp_lr
	comp_lr(plot_data, exp_data, "lr_plot", "lr_stat", "Experimental", "Model", "", true);
	
	if(!options["err_bar"]){
		plot_it([exp_data, plot_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>"], ["#4BB2C5", "#EAA228"]);
		return;
	}
	
	//plot errbar	
	var err_data_input = $("#error_data").val();
	var err_data = new Array();
	
	var err_data_arr = new Array();
	if (!err_data_input) {
		for (var i = 0; i < options["data_num"]; ++i) {
			err_data[i] = "0.000";
		}
	}
	else {
		err_data = trim(err_data_input).split("\n");
	}
	
	var ohlc_data = new Array();
	var flt_err;
	for(var i=0;i<err_data.length && i<options["data_num"]; ++i){
		flt_err = parseFloat(err_data[i]);
		//						high					low			   close
		ohlc_data[i] = [i+1, exp_data[i]+flt_err, exp_data[i]-flt_err, 0];
		
	}
	
	plot_it_errbar([exp_data, plot_data, ohlc_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>", "<b class=\"legend_per\">Experimental error</b>"], -7, ["#4BB2C5", "#EAA228"]);
}

function show_matrix(div_name, matr_base, matr_heads){
	var matr_div = $('#'+div_name).html('');
	var matr_tab = $('<table>').attr('border', '1').css({"margin-right":"auto","margin-left":"auto"});
	
	//first row
	var tab_row = $('<tr>').append(
								$('<td>').html("&nbsp;").css('width', '15px')
						  ).append(
						  		$('<td>').html("&nbsp;")
						  );
	for(var i=0; i<matr_base.length; ++i){
		if (matr_base[i] + 0.0001 < 0) {
			tab_row.append($('<td>').html("<b style=\"color:red;\">" + matr_base[i].toFixed(3) + "</b>"))
		}
		else {
			if (matr_base[i] - 0.0001 < 0){
					tab_row.append($('<td>').html("0.000"))
			}else
				tab_row.append($('<td>').html(matr_base[i].toFixed(3)))
		}
	}
	matr_tab.append(tab_row);
	
	//second row
	tab_row = $('<tr>').append(
					  		$('<th>').html('<b style="color:white;">$$$$$</b>')
					  ).append(
					  		$('<th>').html("SNP3")
					  );
	for(var i=0; i<matr_heads.length; ++i){
		tab_row.append( $('<th>').html(matr_heads[i]) );
	}
	matr_tab.append(tab_row);
	
	//the rest rows
	matr_len = matr_base.length;
	for(var i=0; i<matr_len; ++i){
		tab_row = $("<tr>");
		if (matr_base[matr_len - i - 1] + 0.0001 < 0) {
			tab_row.append($('<td>').html("<b style=\"color:red;\">" + matr_base[matr_len - i - 1].toFixed(3) + "</b>"))
		}
		else {
			if (matr_base[matr_len - i - 1] - 0.0001 < 0){
					tab_row.append($('<td>').html("0.000"))
			}else
				tab_row.append($('<td>').html(matr_base[matr_len - i - 1].toFixed(3)))
		}
		tab_row.append( $('<th>').html(matr_heads[matr_len-i-1]) );
		for(var j=0; j<matr_len; ++j){
			var cell_val = matr_base[j]*matr_base[matr_len-i-1];
			if(cell_val+0.0001<0){
				tab_row.append( $('<td>').html('<b style="color:red;">'+cell_val.toFixed(3)+'</b>') );
			}else{
				if (cell_val - 0.0001 < 0){
					tab_row.append($('<td>').html("0.000"))
				}else
					tab_row.append( $('<td>').html(cell_val.toFixed(3)) );
			}
		}
		matr_tab.append(tab_row);
	}

	matr_div.append(matr_tab);
}

function comp_model_pta(paras, options){
//	alert(paras);
	var ld_ret_obj = comp_3rd_order_ld(paras);
	var paras = ld_ret_obj["paras"];
	var matr_base = ld_ret_obj["matr_base"];
	var dabm = ld_ret_obj["dabm"];
	var no_solution = ld_ret_obj["solution"];
	ld_ret_obj = null;
	
	show_matrix('matr_div', matr_base, [ "P(ATM)","P(AtM)","P(aTM)","P(atM)","P(ATm)","P(Atm)","P(aTm)","P(atm)"]);
	
	//show calculated
	$("#para_Pa").html(paras[2].toFixed(3));
	$("#para_Pb").html(paras[4].toFixed(3));
	$("#para_Pc").html("-");
	$("#para_Pm").html(paras[6].toFixed(3));
	$("#para_DAM").html(paras[9].toFixed(3));
	$("#para_DBM").html(paras[11].toFixed(3));
	$("#para_DCM").html("-");
	$("#para_DAB").html(paras[13].toFixed(3));
	$("#para_DAC").html("-");
	$("#para_DBC").html("-");
	if(no_solution){
		$("#para_DABM").html("<b style=\"color:red\">No Solution(0.000)</b>")
	}else{
		$("#para_DABM").html(dabm.toFixed(3));
	}
	$("#para_DACM").html("-");
	$("#para_DBCM").html("-");
	$("#para_DABC").html("-");
	$("#para_DABCM").html("-");
	
	//frequency array
	// -j 0 j
	var freq_arr = new Array();
	freq_arr[0] = matr_base[2]*matr_base[4]*2;
	freq_arr[1] = (matr_base[2]*matr_base[5] + matr_base[3]*matr_base[4])*2
	freq_arr[2] = matr_base[3]*matr_base[5]*2;
	freq_arr[3] = ( matr_base[2]*matr_base[7] + matr_base[3]*matr_base[7]+ matr_base[2]*matr_base[6] + matr_base[3]*matr_base[6]
				  + matr_base[0]*matr_base[5]+ matr_base[1]*matr_base[4] + matr_base[1]*matr_base[5]+ matr_base[0]*matr_base[4])*2
	freq_arr[4] = matr_base[1]*matr_base[7]*2;
	freq_arr[5] = (matr_base[0]*matr_base[7] + matr_base[1]*matr_base[6])*2
	freq_arr[6] = matr_base[0]*matr_base[6]*2;
	
	var freq_arr_orig = new Array();
	for(var i in freq_arr){
		freq_arr_orig[i] = freq_arr[i];
	}
	
//	alert(freq_arr);
	var freq_sum = 0.0;
	for(var i in freq_arr){
		if(freq_arr[i] < 0.0001){
			freq_arr[i] = 0.0;
		}
		freq_sum += freq_arr[i];
	}

	var scale_ratio = options["data_num"] / freq_sum;
	old_ratio = options["data_num"] / freq_sum;
	if (new_ratio > 0) {
		scale_ratio = new_ratio;
	}
	//scale freq_arr
	var scaled_sum = scale_freq(scale_ratio, freq_arr, options["data_num"]);
	
	//aei array
	var aei_arr = new Array();
	aei_arr[0] = -1*paras[0]-2*paras[7];
	aei_arr[1] = -1*paras[0]-paras[7];
	aei_arr[2] = -1*paras[0];
	aei_arr[3] = 0.010001;
	aei_arr[4] = paras[0]
	aei_arr[5] = paras[0]+paras[7];
	aei_arr[6] = paras[0]+2*paras[7];
	
	key_arr = ["-j-2m", "-j-m", "-j", "0", "j", "j+m", "j+2m"]
	show_jkl_matr("jkl_matr_div", key_arr, freq_arr_orig, freq_arr, aei_arr, scale_ratio, options["data_num"], scaled_sum);
	
	var plot_data = new Array();
	for(var i=0,k=0; i<freq_arr.length; ++i){
		for(var j=0; j<freq_arr[i]; ++j,++k){
			plot_data[k] = aei_arr[i];
		}
	}
	plot_data.sort(function(a,b){return a-b;});
//	alert(plot_data);
	
	if(!options["exp_plot"]){
		show_model_plot(plot_data, "comp_plot_div", options["data_num"]);
		return
	}
	
	input = document.getElementById("exp_data").value;
	input = trim(input);
	var input_data = input.split("\n");
	var ticks = new Array();
	var exp_data = new Array();
	for(i=0; i<input_data.length && i<options["data_num"]; ++i)
	{
		ticks[i] = (i+1);
		exp_data[i] = parseFloat(input_data[i]);
	}
	
	//comp_lr
	comp_lr(plot_data, exp_data, "lr_plot", "lr_stat", "Experimental", "Model", "", true);
	
	if(!options["err_bar"]){
		plot_it([exp_data, plot_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>"], ["#4BB2C5", "#EAA228"]);
		return;
	}
	
	//plot errbar	
	var err_data_input = $("#error_data").val();
	var err_data = new Array();
	
	var err_data_arr = new Array();
	if (!err_data_input) {
		for (var i = 0; i < options["data_num"]; ++i) {
			err_data[i] = "0.000";
		}
	}
	else {
		err_data = trim(err_data_input).split("\n");
	}
	
	var ohlc_data = new Array();
	var flt_err;
	for(var i=0;i<err_data.length && i<options["data_num"]; ++i){
		flt_err = parseFloat(err_data[i]);
		//						high					low			   close
		ohlc_data[i] = [i+1, exp_data[i]+flt_err, exp_data[i]-flt_err, 0];
		
	}
	
	plot_it_errbar([exp_data, plot_data, ohlc_data], ticks, "comp_plot_div", ["<b class=\"legend_per\">Experiment data</b>", "<b class=\"legend_per\">Model</b>", "<b class=\"legend_per\">Experimental error</b>"], -7, ["#4BB2C5", "#EAA228"]);
}


//compute linear regression
function comp_lr(values_x, values_y, plot_div_id, stat_div_id, x_label, y_label, title, show_line) {
	
	//sort values_y against values_x
	var pair_xy = new Array();
	for(var i=0; i<values_x.length; ++i){
		pair_xy[i] = [values_x[i], values_y[i]];
	}
	pair_xy.sort();
	for(var i=0; i<values_x.length; ++i){
		values_x[i] = pair_xy[i][0];
		values_y[i] = pair_xy[i][1];
	}
	
	glo_lr_info[plot_div_id] = [values_x, values_y, plot_div_id, stat_div_id, x_label, y_label, title, show_line];
	
    var sum_x = 0;
    var sum_y = 0;
    var sum_xy = 0;
    var sum_xx = 0;
    var count = 0;
    
    /*
     * We'll use those variables for faster read/write access.
     */
    var x = 0;
    var y = 0;
    var values_length = values_x.length;
    if (values_length != values_y.length) {
        throw new Error('The parameters values_x and values_y need to have same size!');
    }
    
    /*
     * Nothing to do.
     */
    if (values_length === 0) {
        return [ [], [] ];
    }
    
    /*
     * Calculate the sum for each of the parts necessary.
     */
    for (var v = 0; v < values_length; v++) {
        x = values_x[v];
        y = values_y[v];
        sum_x += x;
        sum_y += y;
        sum_xx += x*x;
        sum_xy += x*y;
        count++;
    }
    
    /*
     * Calculate m and b for the formular:
     * y = x * m + b
     */
    var m = (count*sum_xy - sum_x*sum_y) / (count*sum_xx - sum_x*sum_x);
    var b = (sum_y/count) - (m*sum_x)/count;
    
    /*
     * We will make the x and y result line now
     */
    var result_values_x = [];
    var result_values_y = [];
	var rr_1 = 0.0;
	var rr_2 = 0.0;
	var points = [];
    
    for (var v = 0; v < values_length; v++) {
        x = values_x[v];
        y = x * m + b;
		rr_1 += (y-sum_y/count)*(y-sum_y/count);
		rr_2 += (values_y[v]-sum_y/count)*(values_y[v]-sum_y/count);
		points[v] = [values_x[v], values_y[v]];
    }
    
//	$("#lr_plot").html("m:"+m+"\tb:"+b+"\trr:"+rr_1/rr_2);
	
	//plot lr graph
	$("#"+ plot_div_id).html("");
	
/*	
			<table>
			<tr>
				<th align="left">linear regression:</th>
				<td><input type="checkbox" checked=="checked" id="tab2_lr_cb" /></td>
			</tr>
			<tr>
				<th align="right">slope =</th>
				<td id="lr_slope"></td>
			</tr>
			<tr>
				<th align="right">R<sup>2</sup> =</th>
				<td id="tab2_lr_r2"></td>
			</tr>
			<tr>
				<th align="right">P-value =</th>
				<td id="tab2_lr_pval"></td>
			</tr>
		</table>
*/	
	$("#"+stat_div_id).html("");
	var lr_cb = $("<input type='checkbox' checked='checked'>").click(change_lr);
	if(!show_line){
		lr_cb = $("<input type='checkbox'>").click(change_lr);
	}
	$("#"+stat_div_id).append($("<table>")
					  		  .append($("<tr>")
					  		  		  .append($("<th>").css("align","left").html("linear regression:"))
									  .append($("<td>")
									  		  .append(lr_cb)
									         )
							         )
							  .append($("<tr>")
							  		  .append($("<th>").css("align", "right").html("slope ="))
									  .append($("<td>").html(m.toFixed(3))
									         )
									 )
							  .append($("<tr>")
							  		  .append($("<th>").css("align", "right").html("R<sup>2</sup> ="))
									  .append($("<td>").html((rr_1/rr_2).toFixed(3))
									      	 )
									 )
							  .append($("<tr>")
							  		  .append($("<th>").css("align", "right").html("P-value ="))
									  .append($("<td>").html()
									    	 )
									 )
							)

//	$("#lr_stat").html("<b>Slope</b>:"+m.toFixed(3)+"    <b>Intercept</b>:"+b.toFixed(3)+"    <b>r^2</b>:"+(rr_1/rr_2).toFixed(3))
	var line_st_ed = [[values_x[0], values_x[0]*m+b], [values_x[values_length-1], values_x[values_length-1]*m+b]];

	$("#"+plot_div_id).html("");
	
	var data = [points];
	var series = [{
					markerOptions: {style: "filledCircle"},
					showLine: false,
				  }];
	if(show_line){
		data[1] = line_st_ed;
		series[1] = {
						renderer: $.jqplot.LineRenderer,
						lineWidth: 2,
						showMarker: false,
					};
	}
	$.jqplot(plot_div_id, data, {
		title: title,
		seriesDefaults:{
			rendererOptions: {fillToZero: true},
		},
		series:series,
		axes: {
            xaxis: {
                label: x_label,
				labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
		        labelOptions: {
		        	fontFamily: 'Georgia, Serif',
		        },
				tickOptions: {formatString: '%.2f'},
            },
            yaxis: {
                label: y_label,
				labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
				labelOptions: {
	            	fontFamily: 'Georgia, Serif',
	            },
                tickOptions: {formatString: '%.2f'},
            }
        },
		highlighter: {
			show: true,
	//		showMarker:false,
		    tooltipAxes: 'xy',
			useAxesFormatters: true,
		},
	});
}



function show_jkl_matr(div_name, key_arr, freq_arr, freq_arr_scaled, log2aei_arr, scale_ratio, data_num, scaled_sum){
	$("#"+div_name).html("");
	var tab_obj = $("<table>").attr({"border":"1px"}).css({"margin-right":"auto","margin-left":"auto"});
	var row_1 = $("<tr>").append($("<th>").html(""));
	var row_2 = $("<tr>").append($("<th>").html("Frequency"));
	var row_3 = $("<tr>").append($("<th>").html("Number"));
	var row_4 = $("<tr>").append($("<th>").html("Log<sub>2</sub>AEI"));
	var sum1 = 0.0;
	var sum2 = 0.0;
	for(var i=0; i<key_arr.length; ++i){
		row_1.append($("<th>").html(key_arr[i]));
		if(freq_arr[i]+0.0001>0 && freq_arr[i]-0.0001<0){
			row_2.append( $("<td>").html("0.000") );
		}else
			row_2.append( $("<td>").html(freq_arr[i].toFixed(3)) );
		row_3.append( $("<td>").html(freq_arr_scaled[i].toFixed(3)) );
		row_4.append( $("<td>").html(log2aei_arr[i].toFixed(2)) );
		sum1 += freq_arr[i];
		sum2 += freq_arr_scaled[i];
	}
	row_1.append($("<th>").html("Sum"));
	row_2.append($("<td>").html(sum1.toFixed(3)))
	var scaled_sum_td = $("<td>").html(sum2.toFixed(3)).attr("id", "scaled_sum")
	if(Math.abs(scaled_sum-data_num)>0.01){
		scaled_sum_td.css("color", "red");
	}else{
		scaled_sum_td.css("color", "black");
	}
	row_3.append(scaled_sum_td);
	row_4.append($("<td>").html(""))
	tab_obj.append(row_1).append(row_2).append(row_3).append(row_4);
	$("#"+div_name).append(tab_obj);
	var adjust_div = $('<div>').append($('<b>').html("Scale Ratio: "+old_ratio.toFixed(3)))
							   .append($('<b>').html('&nbsp;&nbsp;&nbsp;&nbsp;Data num: ' + data_num)).append($('<br>'))
							   .append($('<b>').html('New Ratio: '))
							   .append($('<input type="text" class="ratio_input">').val(scale_ratio.toFixed(3)))
							   .append($('<input type="button" class="ratio_ok" value="OK!">'))
							   .append($('<input type="button" class="ratio_reset" value="RESET!">'))
	$("#"+div_name).append(adjust_div);
	$("#"+div_name+' .ratio_ok').bind("click", {div_name:div_name}, change_scale_ratio);
	$("#"+div_name+' .ratio_reset').bind("click", {div_name:div_name}, reset_scale_ratio);
	$("#"+div_name+' .ratio_input').keyup(function(event){
  		if(event.keyCode == 13){
    		$("#"+div_name+' .ratio_ok').click();
  		}
	});
	$("#"+div_name+" .ratio_input").focus();
}

function change_scale_ratio(event){
	if (event.data.div_name == "jkl_matr_div") {
		new_ratio = parseFloat($('#jkl_matr_div .ratio_input').val())
		comp_model();
	}
	else if (event.data.div_name == "tab3_jkl_matr_div") {
		glo_tab3_new_ratio = parseFloat($('#tab3_jkl_matr_div .ratio_input').val())
		comp_lr_compare();
	}
}

function reset_scale_ratio(event){
	if (event.data.div_name == "jkl_matr_div") {
		new_ratio = -1;
		comp_model();
	}
	else if (event.data.div_name == "tab3_jkl_matr_div") {
		glo_tab3_new_ratio = -1
		comp_lr_compare();
	}
}

function change_lr(){
	var lr_plot_id = this.parentElement.parentElement.parentElement.parentElement.parentElement.previousElementSibling.id;
	var parameters = glo_lr_info[lr_plot_id];
	comp_lr(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], !parameters[7])
	return;
}

function change_div(){
	var choice = $('#matr_comp_sel').val();
	if(choice=='graph'){
		$('#comp_grid').css('display', 'block');
		$('#matr_grid').css('display', 'none');
	}else if(choice=='matrix'){
		$('#comp_grid').css('display', 'none');
		$('#matr_grid').css('display', 'block');
	}
}

function change_tab3_div(){
	var choice = $('#tab3_matr_comp_sel').val();
	if(choice=='graph'){
		$('#tab3_lr_grid').css('display', 'block');
		$('#tab3_matr_grid').css('display', 'none');
	}else if(choice=='matrix'){
		$('#tab3_lr_grid').css('display', 'none');
		$('#tab3_matr_grid').css('display', 'block');
	}
}

function change_by_trans(){
	var is_checked = $("#pta_model_cb").attr("checked");
	if(is_checked){
		$("#para_PB_tit").html("P(T): ");
		$("#para_Pb_tit").html("P(t): ");
		$("#para_DDBM_tit").html("D'(TM): ");
		$("#para_DDAB_tit").html("D'(AT): ");
		$("#para_DBM_tit").html("D(TM): ");
		$("#para_DAB_tit").html("D(AT): ");
		$("#para_DABM_tit").html("D(ATM): ");
	}else{
		$("#para_PB_tit").html("P(B): ");
		$("#para_Pb_tit").html("P(b): ");
		$("#para_DDBM_tit").html("D'(BM): ");
		$("#para_DDAB_tit").html("D'(AB): ");
		$("#para_DBM_tit").html("D(BM): ");
		$("#para_DAB_tit").html("D(AB): ");
		$("#para_DABM_tit").html("D(ABM): ");
	}
}

function enlarge_plot(){
	org_width = $("#comp_plot_div").css("width")
	float_org_width = parseFloat(org_width)
	new_org_width = float_org_width*1.2
	$("#comp_plot_div").css("width", new_org_width)
	comp_model()
}

function ensmall_plot(){
	org_width = $("#comp_plot_div").css("width")
	float_org_width = parseFloat(org_width)
	new_org_width = float_org_width*0.8
	$("#comp_plot_div").css("width", new_org_width)	
	comp_model()
}

function reset_plot(){
	$("#comp_plot_div").css("width", "100%");
	comp_model()
}

function set_text_area_input_width(){
	var inputs = trim($("#tab3_delta_ct_data").val()).split("\n")
	for(var i=0; i<inputs.length; ++i){
		inputs[i] = parseFloat(inputs[i]).toFixed(5)
	}
	$("#tab3_delta_ct_data").val(inputs.join("\n"));
}

//init
$(function() {
	var today = new Date();
	$("#tit_date1, #tit_date2").text("Date: "+today.getFullYear()+(today.getMonth()+1)+today.getDate());
	$("#tabs").tabs();
	$("#show_err_bar_exp").bind("click", show_exp_plot);
	
	glo_stored_items =  $("#input_tab_1 input, #input_tab_2 input, #tab3_input_tab_1 input, #tab3_input_tab_2 input, #tab3_exp_input_div input[type=text]");
	glo_stored_volatile_items =  $("#exp_data, #error_data, #tab3_exp_input_div textarea");
	
	for(var i=0; i<glo_stored_volatile_items.length; ++i){
		glo_stored_volatile_items[i].value = window.localStorage.getItem(glo_stored_volatile_items[i].id);
	}
	
	for(var i=0; i<glo_stored_items.length; ++i){
		glo_stored_items[i].value = window.localStorage.getItem("para"+i);
	}
	$("#comp_show_err_bar_cb").bind("click", comp_model);
	$("#comp_show_exp_cb").bind("click", comp_model);
	$("#comp_show_model_cb").bind("click", comp_model);
	$('#matr_comp_sel').change(change_div);
	$('#tab3_matr_comp_sel').change(change_tab3_div);
	$("#pta_model_cb").bind("click", change_by_trans);
	
	//gen data_num select
	$("#compare_num_sel").change(comp_model);
	for(var i=1; i<101; ++i){
		$("#compare_num_sel").append("<option value=\""+i+"\">"+i+"</option>")
	}
	
	$("#tab3_delta_ct_data").blur(set_text_area_input_width);
	
//	setInterval("auto_save()", 180000);
//	comp_lr([0,6,12,18],[100.1,98.1,95.9,91]);
});
